﻿using System;

namespace ContextualStateless
{
    static class ParameterConversion
    {
        public static object Unpack(object[] args, Type argType, int index)
        {
            Enforce.ArgumentNotNull( args, "args" );
//            Contract.Requires( args != null, "args" );
//            Contract.Requires< ArgumentException >( args.Length <= index, string.Format( ParameterConversionResources.ArgOfTypeRequiredInPosition, argType, index ) );
//            Contract.EnsuresOnThrow<ArgumentException>( args[ index ] != null && !argType.IsAssignableFrom( args[ index ].GetType() ), string.Format( ParameterConversionResources.WrongArgType, index, args[ index ].GetType(), argType ) );

            if (args.Length <= index)
                throw new ArgumentException( string.Format(ParameterConversionResources.ArgOfTypeRequiredInPosition, argType, index) );

            var _arg = args[ index ];

            if (_arg != null && !argType.IsAssignableFrom(_arg.GetType()))
                throw new ArgumentException( string.Format(ParameterConversionResources.WrongArgType, index, _arg.GetType(), argType) );

            return _arg;
        }

        public static TArg Unpack<TArg>(object[] args, int index)
        {
            return (TArg)Unpack(args, typeof(TArg), index);
        }

        public static void Validate(object[] args, Type[] expected)
        {
//            Contract.Requires( args != null, "args" );
//            Contract.Requires( expected != null, "expected" );
//            Contract.Requires< ArgumentException >( args.Length <= expected.Length, string.Format( ParameterConversionResources.TooManyParameters, expected.Length, args.Length ) );

            if (args.Length > expected.Length)
                throw new ArgumentException( string.Format(ParameterConversionResources.TooManyParameters, expected.Length, args.Length) );

            for (int i = 0; i < expected.Length; ++i)
                Unpack(args, expected[i], i);
        }
    }
}
